package com.chen.base.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 基本mvc配置
 * @author Long
 */
@EnableAsync
@EnableCaching
@Configuration
@EnableScheduling
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class BaseWebMvcConfig implements WebMvcConfigurer {

	/**
	 * 跨域过滤器
	 */
	@Bean
	public CorsFilter corsFilter() {
		CorsConfiguration cors = new CorsConfiguration();
		// 是否允许跨域发送cookie
		cors.setAllowCredentials(true);
		// 允许访问的客户端域名
		// cors.addAllowedOrigin("*"); SpringBoot升级成2.4.0以上时对AllowedOrigin设置发生了改变，不能有”*“
		cors.addAllowedOriginPattern("*");
		// 允许服务端访问的客户端请求头
		cors.addAllowedHeader("*");
		// 允许的请求方法
		cors.addAllowedMethod("*");
		// 预检验请求有效时间, 单位：秒
		cors.setMaxAge(3600L);

		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", cors);
		return new CorsFilter(source);
	}

	/**
	 * 静态资源目录配置
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//添加默认的静态资源访问路径
		registry.addResourceHandler("/**")
				.addResourceLocations(
						"classpath:static/",
						"classpath:META-IFA/resources/",
						"classpath:resources/",
						"classpath:public/",
						"classpath:/"
				);
	}
}